﻿using ComTools.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SuperSocketClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_send_Click(object sender, EventArgs e)
        {
            ///请求参数
            string sendStr = "{\"keyWords\":\"123123\",\"beginIndex\":0,\"rowsNum\":30}";
            if (string.IsNullOrWhiteSpace(sendStr))
            {
                txt_result.Text = "请输入请求参数";
                return;
            }
            if (!JsonHelper.IsJson(sendStr))
            {
                txt_result.Text = "请输入JSON格式的请求参数";
                return;
            }
            Task.Run(()=> {
                string resultStr = socketOpt(sendStr,10);
                //这里不用实体接收，只做类内部改造，不在项目中添加其他多余代码
                //var resultInfo = JsonHelper.JSONToObject<Dictionary<string, object>>(resultStr);
                SetValue(txt_result, resultStr);
            });
        }


        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="textBox"></param>
        /// <param name="msg"></param>
        private void SetValue(TextBox textBox, string msg)
        {
            BeginInvoke(new Action(() =>
            {
                textBox.Text = msg;
            }));
        }

        /// <summary>
        /// optType
        /// </summary>
        /// <param name="message"></param>
        /// <param name=""></param>
        /// <returns></returns>
        private string socketOpt(string message,int optType)
        {

            string recvStr = string.Empty;

            var webSocketUrl = System.Configuration.ConfigurationManager.AppSettings["WebSocketURL"];
            var webSocketPort = System.Configuration.ConfigurationManager.AppSettings["WebSocketPort"];

            IPAddress ip = IPAddress.Parse(webSocketUrl);
            IPEndPoint ipe = new IPEndPoint(ip, Convert.ToInt32(webSocketPort));
            Socket clientSocket = null;

            using (clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                clientSocket.Connect(ipe); //配置服务器IP与端口 

                #region 拼装需要发送的信息
                //string message = "{\"keyWords\":\"加油机\",\"beginIndex\":0,\"rowsNum\":59}";
                //拼接命令头 10 或 11
                var response = BitConverter.GetBytes((ushort)optType).Reverse().ToList();
                var arr = System.Text.Encoding.UTF8.GetBytes(message);
                response.AddRange(BitConverter.GetBytes((ushort)arr.Length).Reverse().ToArray());
                response.AddRange(arr);
                #endregion

                #region 发送并接收消息
                clientSocket.Send(response.ToArray());
                byte[] resultInfo = new byte[10240];
                int indexNum = 0;
                int delayTime = 0;
                while (true)
                {
                    if (clientSocket.Connected)
                    {
                        //接受从服务器返回的信息
                        if (clientSocket.Poll(0, SelectMode.SelectRead) && clientSocket.Available > 0)
                        {
                            byte[] recvBytes = new byte[clientSocket.Available];
                            int bytes = clientSocket.Receive(recvBytes);//从服务器端接受返回信息
                            recvBytes.CopyTo(resultInfo, indexNum);
                            indexNum += bytes;
                        }
                        else
                        {
                            //获取长度
                            if (indexNum >= 4)
                            {
                                recvStr = Encoding.UTF8.GetString(resultInfo, 4, indexNum - 4);
                                break;

                            }
                            if (delayTime >= 5000)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                    Thread.Sleep(50);
                    delayTime += 50;
                }
                return recvStr;
                #endregion
            }

        }
    }
}
